import sys
import pygame
import random  # 确保导入了random模块

# 初始化Pygame
pygame.init()

# 设置中文字体
pygame.font.init()
font = pygame.font.SysFont(["SimHei", "WenQuanYi Micro Hei", "Heiti TC"], 30)

# 游戏常量
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 480
FPS = 60
GRAVITY = 0.6
PLAYER_JUMP_POWER = -13
PLAYER_SPEED = 5

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
BROWN = (139, 69, 19)
SKY_BLUE = (135, 206, 235)

# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("简单马里奥游戏")
clock = pygame.time.Clock()


class Player(pygame.sprite.Sprite):
    """玩家类"""

    def __init__(self, x=100, y=SCREEN_HEIGHT - 100):
        super().__init__()
        # 将角色高度从57像素进一步缩小为54像素
        self.image = pygame.Surface((30, 54))
        self.image.fill(BLUE)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.velocity_y = 0
        self.velocity_x = 0
        self.on_ground = False
        self.lives = 3  # 玩家初始生命值
        self.score = 0
        self.game_over = False  # 添加这个属性来标记游戏结束状态
        # 新增：道具状态属性
        self.fly_powerup = False
        self.fly_timer = 0
        self.invincible = False
        self.invincible_timer = 0

        # 新增：暂停状态属性
        self.spawn_pause = False  # 出生点暂停状态
        self.spawn_pause_timer = 0  # 出生点暂停计时器

        # 新增：二段跳相关属性
        self.jump_count = 0  # 已使用的跳跃次数
        self.max_jumps = 2  # 最大跳跃次数（普通跳跃 + 二段跳）

    def update(self, platforms, enemies, question_blocks):
        """更新玩家状态"""
        # 检查是否处于出生点暂停状态
        if self.spawn_pause:
            self.spawn_pause_timer -= 1
            # 暂停0.5秒（30帧）
            if self.spawn_pause_timer <= 0:
                self.spawn_pause = False
            # 暂停期间不更新移动和输入
            return []

        # 如果还需要保留道具系统，则保留这些调用
        # self.update_powerups()
        self.update_appearance()

        # 保留原有的update方法逻辑
        # 应用重力
        self.velocity_y += GRAVITY

        # 左右移动
        self.velocity_x = 0
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.velocity_x = -PLAYER_SPEED
        if keys[pygame.K_RIGHT]:
            self.velocity_x = PLAYER_SPEED

        # 检查跳跃按键
        if keys[pygame.K_SPACE]:
            self.jump()

        # 移动玩家
        self.rect.x += self.velocity_x

        # 水平碰撞检测
        for platform in platforms:
            if self.rect.colliderect(platform.rect):
                if self.velocity_x > 0:  # 向右移动
                    self.rect.right = platform.rect.left
                elif self.velocity_x < 0:  # 向左移动
                    self.rect.left = platform.rect.right

        # 垂直移动
        self.rect.y += self.velocity_y
        self.on_ground = False

        # 垂直碰撞检测 - 平台
        for platform in platforms:
            if self.rect.colliderect(platform.rect):
                if self.velocity_y > 0:  # 下落
                    self.rect.bottom = platform.rect.top
                    self.on_ground = True
                    self.velocity_y = 0
                    # 落地时重置跳跃计数器，允许再次跳跃
                    self.jump_count = 0
                elif self.velocity_y < 0:  # 上升（顶砖块）
                    self.rect.top = platform.rect.bottom
                    self.velocity_y = 0

        # 敌人碰撞检测
        for enemy in enemies:
            if self.rect.colliderect(enemy.rect):
                if self.is_above_enemy(enemy):
                    # 从上方踩敌人
                    self.velocity_y = PLAYER_JUMP_POWER // 2  # 小跳跃
                    enemy.kill()
                    self.score += 100
                else:
                    # 被敌人碰到
                    self.lives -= 1
                    # 修复：确保玩家失去所有生命后立即结束游戏
                    if self.lives <= 0:
                        # 确保生命值不会变为负数
                        self.lives = 0
                        # 设置游戏结束状态
                        self.game_over = True  # 添加这个属性
                    else:
                        # 重置玩家位置
                        self.rect.x = 100
                        self.rect.y = SCREEN_HEIGHT - 100
                        self.velocity_y = 0
                        # 启动出生点暂停
                        self.spawn_pause = True
                        self.spawn_pause_timer = 30  # 0.5秒（60FPS下30帧）

        # 问号砖块碰撞检测 - 保留顶砖块和踩砖块都能触发的功能
        collected_coins = []
        for block in question_blocks:
            if self.rect.colliderect(block.rect):
                if self.velocity_y > 0:  # 下落（踩砖块）
                    self.rect.bottom = block.rect.top
                    self.on_ground = True
                    self.velocity_y = 0
                    # 踩砖块也能触发砖块效果
                    coin = block.hit()
                    if coin:
                        collected_coins.append(coin)
                elif self.velocity_y < 0:  # 上升（顶砖块）
                    self.rect.top = block.rect.bottom
                    self.velocity_y = 0
                    # 顶砖块触发砖块效果
                    coin = block.hit()
                    if coin:
                        collected_coins.append(coin)

        return collected_coins

    def jump(self):
        """玩家跳跃 - 修改为支持二段跳"""
        if self.jump_count < self.max_jumps:
            # 第一次跳跃使用完整的跳跃力量，第二次跳跃使用稍小的力量，让二段跳更合理
            jump_power = PLAYER_JUMP_POWER
            if self.jump_count > 0:
                jump_power = PLAYER_JUMP_POWER * 0.8  # 二段跳力量稍小

            self.velocity_y = jump_power
            self.jump_count += 1
            self.on_ground = False

    def is_above_enemy(self, enemy):
        """检查玩家是否在敌人上方，可以踩死敌人"""
        # 玩家底部是否碰到敌人顶部，并且玩家正在下落
        return (self.rect.bottom >= enemy.rect.top and
                self.rect.bottom <= enemy.rect.top + 10 and
                self.velocity_y > 0)

    def apply_powerup(self, power_type):
        """应用道具效果"""
        if power_type == 'fly':
            self.fly_powerup = True
            self.fly_timer = 300  # 300帧（约5秒）
        elif power_type == 'life':
            self.lives += 1
        elif power_type == 'invincible':
            self.invincible = True
            self.invincible_timer = 600  # 600帧（约10秒）
            # 播放无敌音效（如果有）
            # pygame.mixer.Sound('invincible.wav').play()

    def update_powerups(self):
        """更新道具效果时间"""
        # 更新飞行道具时间
        if self.fly_powerup:
            self.fly_timer -= 1
            if self.fly_timer <= 0:
                self.fly_powerup = False

        # 更新无敌道具时间
        if self.invincible:
            self.invincible_timer -= 1
            if self.invincible_timer <= 0:
                self.invincible = False

    def update_appearance(self):
        """根据道具状态更新玩家形象"""
        # 尝试重新加载马里奥精灵图片 - 使用正确的相对路径
        try:
            self.image = pygame.image.load(
                'FCC/Python/game/mario_sprite.png').convert_alpha()
            # 如果需要调整图片大小，可以添加下面这行
            # self.image = pygame.transform.scale(self.image, (30, 60))
        except pygame.error:
            # 如果图片加载失败，使用默认的蓝色方块作为备用
            self.image = pygame.Surface((30, 60))
            self.image.fill(BLUE)

        # 重新设置rect以确保它与新image匹配
        old_center = self.rect.center
        self.rect = self.image.get_rect()
        self.rect.center = old_center


class Platform(pygame.sprite.Sprite):
    """平台类"""

    def __init__(self, x, y, width, height, color=GREEN):
        super().__init__()
        self.image = pygame.Surface((width, height))
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y


class Enemy(pygame.sprite.Sprite):
    """敌人类 - 代表游戏中的蘑菇怪、乌龟等敌人"""

    def __init__(self, x, y, enemy_type="goomba"):
        super().__init__()
        self.enemy_type = enemy_type
        # 创建简单的敌人图形
        if enemy_type == "goomba":
            self.image = pygame.Surface((32, 32))
            self.image.fill(RED)
            self.base_speed = 2  # 降低基础速度，从5调整为2
        elif enemy_type == "turtle":
            self.image = pygame.Surface((36, 24))
            self.image.fill(GREEN)
            self.base_speed = 1.5  # 降低基础速度，从4调整为1.5

        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        # 随机设置初始方向，使敌人移动更加多样化
        self.direction = 1 if random.random() < 0.5 else -1  # 随机向右或向左
        # 移除重力相关属性，怪物不会掉落
        self.speed = self.base_speed  # 当前速度初始化为基础速度
        self.move_timer = 0  # 用于计时，控制方向和速度变化
        self.turn_cooldown = 0  # 添加翻转冷却计数器，防止频繁翻转

    def update(self, platforms):
        """更新敌人状态 - 实现大幅度移动，包括速度变化和随机转向"""
        # 减少翻转冷却计数
        if self.turn_cooldown > 0:
            self.turn_cooldown -= 1

        # 每100帧随机改变方向和速度，增加移动的不确定性
        self.move_timer += 1
        if self.move_timer >= 100:
            self.move_timer = 0
            # 30%的概率改变方向，但仅在没有冷却时
            if random.random() < 0.3 and self.turn_cooldown == 0:
                self.direction *= -1
                self.turn_cooldown = 30  # 设置30帧的冷却时间
            # 调整速度范围，使整体移动更慢
            self.speed = self.base_speed * \
                (0.7 + random.random() * 0.5)  # 范围从0.7-1.2倍，之前是0.8-1.5倍

        # 尝试移动 - 速度乘以方向
        move_amount = self.speed * self.direction
        self.rect.x += move_amount

        # 检查是否发生碰撞
        collision = False
        for platform in platforms:
            if platform and self.rect.colliderect(platform.rect):
                collision = True
                # 调整位置到平台边缘
                if move_amount > 0:  # 向右移动时碰到平台
                    self.rect.right = platform.rect.left
                else:  # 向左移动时碰到平台
                    self.rect.left = platform.rect.right
                # 翻转方向，但仅在没有冷却时
                if self.turn_cooldown == 0:
                    self.direction *= -1
                    self.turn_cooldown = 20  # 设置20帧的冷却时间
                break

        # 检查屏幕边界
        if self.rect.left <= 0:
            self.rect.left = 0
            if self.turn_cooldown == 0:
                self.direction = 1  # 向右移动
                self.turn_cooldown = 20  # 设置20帧的冷却时间
        elif self.rect.right >= SCREEN_WIDTH:
            self.rect.right = SCREEN_WIDTH
            if self.turn_cooldown == 0:
                self.direction = -1  # 向左移动
                self.turn_cooldown = 20  # 设置20帧的冷却时间

        # 优化平台边缘检测 - 由于大部分平台已移除，简化此逻辑
        if platforms and len(platforms) > 1:  # 仅在有多个平台时才进行边缘检测
            # 计算前方的位置来检测边缘
            front_x = self.rect.right if self.direction > 0 else self.rect.left
            front_y = self.rect.bottom + 1  # 稍微往下一点检测是否有平台

            # 创建一个小矩形来检测前方是否有平台
            front_rect = pygame.Rect(front_x - 5, front_y, 10, 10)

            edge_found = False
            for platform in platforms:
                if front_rect.colliderect(platform.rect):
                    edge_found = True
                    break

            # 如果前方没有平台，并且不在冷却中，则翻转方向
            if not edge_found and self.turn_cooldown == 0:
                self.direction *= -1
                self.turn_cooldown = 25  # 设置25帧的冷却时间


class Coin(pygame.sprite.Sprite):
    """金币类"""

    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface((16, 16))
        self.image.fill(YELLOW)
        pygame.draw.circle(self.image, (255, 215, 0), (8, 8), 7)

        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.velocity_y = -3
        self.gravity = 0.15
        self.on_platform = False  # 新增：标记金币是否在平台上

    def update(self, platforms=None):
        """更新金币位置"""
        if not self.on_platform:  # 如果不在平台上，才应用重力
            self.velocity_y += self.gravity
            self.rect.y += self.velocity_y

        # 如果传入了平台列表，进行平台碰撞检测
        if platforms:
            self.check_platform_collision(platforms)

        # 金币上升到一定高度后不再自动消失
        # 只有当金币掉出屏幕底部才消失
        if self.rect.top > SCREEN_HEIGHT:
            self.kill()

    def check_platform_collision(self, platforms):
        """检查金币与平台的碰撞"""
        for platform in platforms:
            if self.rect.colliderect(platform.rect) and self.velocity_y > 0:
                # 金币下落到平台上
                self.rect.bottom = platform.rect.top
                self.velocity_y = 0
                self.on_platform = True
                break
            elif not self.rect.colliderect(platform.rect) and self.on_platform:
                # 金币离开了平台
                self.on_platform = False


# 首先修改QuestionBlock类的hit方法，使砖块触发后消失
class QuestionBlock(pygame.sprite.Sprite):
    """问号砖块类"""

    def __init__(self, x, y, block_type=None, power_type=None):
        super().__init__()
        self.image = pygame.Surface((32, 32))
        self.image.fill(YELLOW)
        pygame.draw.rect(self.image, BLACK, (0, 0, 32, 32), 2)
        pygame.draw.ellipse(self.image, BLACK, (8, 10, 6, 6))
        pygame.draw.ellipse(self.image, BLACK, (18, 6, 6, 6))
        pygame.draw.ellipse(self.image, BLACK, (18, 14, 6, 6))

        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.hit_count = 0
        self.block_type = block_type
        self.power_type = power_type

    def hit(self):
        """砖块被顶时的反应"""
        if self.hit_count == 0:
            self.hit_count += 1
            # 改变砖块外观
            self.image.fill(GREEN)
            pygame.draw.rect(self.image, BLACK, (0, 0, 32, 32), 2)

            # 根据砖块类型创建不同的物品
            if self.block_type == 'powerup' and self.power_type:
                # 创建道具
                result = PowerUp(self.rect.centerx - 15,
                                 self.rect.y - 30, self.power_type)
            else:
                # 创建金币
                result = Coin(self.rect.centerx - 8, self.rect.y - 16)

            # 触发后使砖块消失
            self.kill()
            return result
        return None

# 然后简化第三关并调整敌人速度


class Level:
    """关卡类"""

    def __init__(self, level_number=1):
        self.platforms = pygame.sprite.Group()
        self.enemies = pygame.sprite.Group()
        self.coins = pygame.sprite.Group()
        self.question_blocks = pygame.sprite.Group()
        self.piranha_plants = pygame.sprite.Group()  # 新增：食人花组
        self.goal = None
        self.powerups = pygame.sprite.Group()  # 新增：初始化道具组

        # 创建关卡
        self.create_level(level_number)

    # 在Level类的create_level方法中简化关卡2
    def create_level(self, level_number):
        if level_number == 1:
            # 蘑菇王国关卡 - 调整为可通关的布局
            # 移除地面平台

            # 出生点平台 - 确保玩家出生时有平台可站
            spawn_platform = Platform(50, SCREEN_HEIGHT - 100, 100, 20)

            # 调整平台布局，确保可通关
            platform1 = Platform(200, SCREEN_HEIGHT - 100, 100, 20)
            # 将平台2的y坐标从SCREEN_HEIGHT - 150调高到SCREEN_HEIGHT - 140
            platform2 = Platform(350, SCREEN_HEIGHT - 140, 100, 20)
            # 将平台3的y坐标从SCREEN_HEIGHT - 200调高到SCREEN_HEIGHT - 190
            platform3 = Platform(500, SCREEN_HEIGHT - 190, 100, 20)
            # 将最高平台platform4的高度增加20像素（y坐标减少20）
            platform4 = Platform(300, SCREEN_HEIGHT - 270, 100, 20)
            platform5 = Platform(650, SCREEN_HEIGHT - 180,
                                 80, 20)   # 新增平台，直接连接到旗子
            self.platforms.add(spawn_platform, platform1,
                               platform2, platform3, platform4, platform5)

            # 问号砖块
            block1 = QuestionBlock(300, SCREEN_HEIGHT - 180)
            block2 = QuestionBlock(450, SCREEN_HEIGHT - 230)
            self.question_blocks.add(block1, block2)

            # 调整敌人位置，减少对主路径的阻碍
            enemy1 = Enemy(250, SCREEN_HEIGHT - 120)  # 调整位置，避免直接阻挡在主路径上
            enemy2 = Enemy(450, SCREEN_HEIGHT - 170)  # 调整位置
            enemy3 = Enemy(150, SCREEN_HEIGHT - 270)  # 放在次要路径上
            self.enemies.add(enemy1, enemy2, enemy3)

            # 终点（旗杆）- 调整位置，使其高于平台
            self.goal = (700, SCREEN_HEIGHT - 220)
        elif level_number == 2:
            # 地下世界关卡（简化版）
            # 移除地面平台

            # 出生点平台 - 确保玩家出生时有平台可站
            spawn_platform = Platform(50, SCREEN_HEIGHT - 100, 100, 20)

            # 保留必要的平台，移除部分复杂平台
            platform1 = Platform(200, SCREEN_HEIGHT - 100, 100, 20)
            platform2 = Platform(400, SCREEN_HEIGHT - 150, 100, 20)
            platform3 = Platform(600, SCREEN_HEIGHT - 200, 100, 20)
            # 保留直接通往终点的平台
            platform4 = Platform(550, SCREEN_HEIGHT - 120, 100, 20)
            self.platforms.add(spawn_platform, platform1,
                               platform2, platform3, platform4)

            # 简化砖块，只保留2个
            block1 = QuestionBlock(250, SCREEN_HEIGHT - 180)  # 普通金币砖块
            block2 = QuestionBlock(450, SCREEN_HEIGHT - 230)  # 普通金币砖块
            self.question_blocks.add(block1, block2)

            # 简化敌人，只保留3个
            enemy1 = Enemy(300, SCREEN_HEIGHT - 120, "turtle")  # 空中乌龟
            enemy2 = Enemy(500, SCREEN_HEIGHT - 220)  # 空中敌人
            enemy3 = Enemy(400, SCREEN_HEIGHT - 170)  # 中间路径敌人
            self.enemies.add(enemy1, enemy2, enemy3)

            self.goal = (600, SCREEN_HEIGHT - 180)
        elif level_number == 3:
            # 城堡关卡（简化版）
            # 移除地面平台

            # 出生点平台 - 确保玩家出生时有平台可站
            spawn_platform = Platform(50, SCREEN_HEIGHT - 120, 100, 20)

            # 简化平台数量，只保留主要路径的平台
            platform1 = Platform(250, SCREEN_HEIGHT - 120, 100, 20)
            platform2 = Platform(450, SCREEN_HEIGHT - 180, 100, 20)
            platform3 = Platform(650, SCREEN_HEIGHT - 240, 100, 20)
            platform4 = Platform(500, SCREEN_HEIGHT - 300, 100, 20)
            self.platforms.add(spawn_platform, platform1,
                               platform2, platform3, platform4)

            # 简化砖块，只保留必要的砖块
            block1 = QuestionBlock(300, SCREEN_HEIGHT - 200)  # 普通金币砖块
            block2 = QuestionBlock(500, SCREEN_HEIGHT - 260)  # 普通金币砖块
            self.question_blocks.add(block1, block2)

            # 减少敌人数量并设置较慢的速度
            enemy1 = Enemy(350, SCREEN_HEIGHT - 140)  # 空中敌人
            enemy1.base_speed = 1.0  # 特别减慢第三关敌人速度
            enemy1.speed = enemy1.base_speed

            enemy2 = Enemy(550, SCREEN_HEIGHT - 200, "turtle")  # 空中乌龟
            enemy2.base_speed = 0.8  # 特别减慢第三关乌龟速度
            enemy2.speed = enemy2.base_speed

            enemy3 = Enemy(200, SCREEN_HEIGHT - 140)  # 新增空中敌人
            enemy3.base_speed = 1.0  # 特别减慢第三关敌人速度
            enemy3.speed = enemy3.base_speed

            self.enemies.add(enemy1, enemy2, enemy3)

            self.goal = (700, SCREEN_HEIGHT - 300)
        elif level_number == 4:
            # 第四关 - 只有平地且表面全部为食人花
            # 创建一个长长的平地
            ground_platform = Platform(
                0, SCREEN_HEIGHT - 50, SCREEN_WIDTH, 50, BROWN)
            self.platforms.add(ground_platform)

            # 在平地上每隔一段距离放置一个食人花
            plant_spacing = 100  # 食人花之间的间距
            for x in range(100, SCREEN_WIDTH - 100, plant_spacing):
                # 将食人花放在平台边缘
                plant_y = SCREEN_HEIGHT - 50 - 20  # 放在平台上方20像素
                plant = PiranhaPlant(x, plant_y)
                # 随机设置初始计时器，使食人花的出现时间错开
                plant.current_timer = random.randint(0, plant.surface_time)
                self.piranha_plants.add(plant)

            # 设置终点，让玩家可以通关
            self.goal = (SCREEN_WIDTH - 100, SCREEN_HEIGHT - 150)

    def update_coins(self):
        """更新所有金币"""
        for coin in self.coins:
            coin.update()

    # 新增：更新所有道具
    def update_powerups(self):
        """更新所有道具的位置和状态"""
        try:
            for powerup in self.powerups:
                if powerup:  # 确保powerup对象有效
                    powerup.update(self.platforms)
        except Exception as e:
            print(f"关卡道具更新错误: {e}")
            # 只记录错误，不中断游戏


class Game:
    """游戏主类"""

    def __init__(self):
        self.current_level = 1
        self.level = Level(self.current_level)
        self.player = Player()
        self.running = True
        self.paused = False
        self.game_over = False
        self.victory = False
        self.font = pygame.font.SysFont(
            ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"], 48)
        self.small_font = pygame.font.SysFont(
            ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"], 24)
        # 新增：三段跳选项相关变量
        self.allow_triple_jump = False
        # 在分数和生命右边放置三段跳按钮
        self.triple_jump_button = pygame.Rect(230, 10, 120, 30)
        self.triple_jump_button_color = (100, 100, 100)
        self.triple_jump_button_hover = (150, 150, 150)
        self.current_button_color = self.triple_jump_button_color

    def handle_events(self):
        """处理游戏事件"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_p:
                    self.paused = not self.paused
                elif event.key == pygame.K_r:
                    self.reset_level()
                elif not self.paused and not self.game_over and not self.victory:
                    if event.key == pygame.K_UP:
                        self.player.jump()
            # 新增：处理鼠标点击事件
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:  # 左键点击
                if not self.paused and not self.game_over and not self.victory:
                    # 检查是否点击了三段跳按钮
                    if self.triple_jump_button.collidepoint(event.pos):
                        self.allow_triple_jump = not self.allow_triple_jump
                        # 根据三段跳是否开启来设置玩家的最大跳跃次数
                        if self.allow_triple_jump:
                            self.player.max_jumps = 3  # 启用三段跳
                        else:
                            self.player.max_jumps = 2  # 恢复为二段跳
            # 新增：处理鼠标悬停事件
            elif event.type == pygame.MOUSEMOTION:
                if self.triple_jump_button.collidepoint(event.pos):
                    self.current_button_color = self.triple_jump_button_hover
                else:
                    self.current_button_color = self.triple_jump_button_color

    def update(self):
        """更新游戏状态"""
        # 更新玩家
        new_coins = self.player.update(
            self.level.platforms, self.level.enemies, self.level.question_blocks)

        # 检查玩家是否标记了游戏结束
        if self.player.game_over:
            self.game_over = True
            return  # 立即结束当前帧的更新

        # 删除道具更新
        # self.player.update_powerups()

        # 添加新金币
        for coin in new_coins:
            self.level.coins.add(coin)

        # 收集金币
        for coin in self.level.coins:
            if self.player.rect.colliderect(coin.rect):
                self.player.score += 50
                coin.kill()

        # 删除道具收集逻辑
        # for powerup in self.level.powerups:
        #     if self.player.rect.colliderect(powerup.rect):
        #         self.player.apply_powerup(powerup.power_type)
        #         powerup.kill()
        #         # 播放收集音效（如果有）
        #         # pygame.mixer.Sound('powerup.wav').play()

        # 更新敌人
        for enemy in self.level.enemies:
            enemy.update(self.level.platforms)

        # 更新金币
        for coin in self.level.coins:
            coin.update(self.level.platforms)

        # 删除道具更新
        # self.level.update_powerups()

        # 检查玩家是否掉出屏幕底部 - 只有从底部掉出才视为死亡
        if self.player.rect.top > SCREEN_HEIGHT:
            self.player.lives -= 1
            if self.player.lives > 0:
                # 重置玩家位置
                if hasattr(self.player, 'checkpoint_x'):
                    # 从存档点复活
                    self.player.rect.x = self.player.checkpoint_x
                    self.player.rect.y = self.player.checkpoint_y
                else:
                    # 从出生点复活
                    self.player.rect.x = 100
                    # 第三关特殊处理
                    if self.current_level == 3:
                        self.player.rect.y = SCREEN_HEIGHT - 130
                    else:
                        self.player.rect.y = SCREEN_HEIGHT - 100
                self.player.velocity_y = 0
                # 启动出生点暂停
                self.player.spawn_pause = True
                self.player.spawn_pause_timer = 30  # 0.5秒（60FPS下30帧）
            else:
                # 生命值为0时设置游戏结束
                self.player.lives = 0  # 确保生命值不会变为负数
                self.game_over = True

        # 检查存档点
        if hasattr(self.level, 'checkpoints'):
            for checkpoint in self.level.checkpoints:
                if self.player.rect.colliderect(checkpoint.rect) and not checkpoint.activated:
                    checkpoint.activate()
                    # 记录存档点位置
                    self.player.set_checkpoint(
                        checkpoint.rect.x, checkpoint.rect.y)
                    # 更新存档点
                    checkpoint.update()

        # 在Game类的update方法中确保食人花碰撞逻辑完整
        # 检查与食人花的碰撞
        if hasattr(self.level, 'piranha_plants'):
            for plant in self.level.piranha_plants:
                plant.update()  # 更新食人花状态
                if self.player.rect.colliderect(plant.rect):
                    # 检查玩家是否在食人花上方（可以踩死）
                    if self.player.is_above_enemy(plant):
                        self.player.velocity_y = PLAYER_JUMP_POWER // 2  # 小跳跃
                        plant.kill()
                        self.player.score += 100
                    else:
                        # 被食人花碰到，减少生命值
                        if not self.player.invincible:  # 如果不是无敌状态
                            self.player.lives -= 1
                            if self.player.lives > 0:
                                # 从存档点或出生点复活
                                if hasattr(self.player, 'checkpoint_x'):
                                    # 从存档点复活
                                    self.player.rect.x = self.player.checkpoint_x
                                    self.player.rect.y = self.player.checkpoint_y
                                else:
                                    # 从出生点复活
                                    self.player.rect.x = 100
                                    # 第三关特殊处理
                                    if self.current_level == 3:
                                        self.player.rect.y = SCREEN_HEIGHT - 130
                                    else:
                                        self.player.rect.y = SCREEN_HEIGHT - 100
                                self.player.velocity_y = 0
                                # 启动出生点暂停
                                self.player.spawn_pause = True
                                self.player.spawn_pause_timer = 30  # 0.5秒（60FPS下30帧）
                            else:
                                # 生命值为0时设置游戏结束
                                self.player.lives = 0  # 确保生命值不会变为负数
                                self.game_over = True

        # 添加终点检测逻辑
        if self.level.goal and not self.game_over and not self.victory:
            # 创建终点区域的rect对象，用于碰撞检测
            # 终点由两部分组成：旗杆(棕色)和顶部方块(红色)
            # 我们检测玩家是否碰到顶部的红色方块
            goal_rect = pygame.Rect(
                self.level.goal[0] - 20, self.level.goal[1], 40, 20)

            # 检查玩家是否与终点区域发生碰撞
            if self.player.rect.colliderect(goal_rect):
                if self.current_level >= 4:  # 修改为4，表示4是最后一关
                    # 最后一关结束，游戏胜利
                    self.victory = True
                else:
                    # 进入下一关
                    self.current_level += 1
                    # 创建新关卡
                    self.level = Level(self.current_level)
                    # 重置玩家位置和状态，但保留生命值和分数
                    self.player.rect.x = 100
                    if self.current_level == 3:
                        self.player.rect.y = SCREEN_HEIGHT - 130
                    else:
                        self.player.rect.y = SCREEN_HEIGHT - 100
                    self.player.velocity_x = 0
                    self.player.velocity_y = 0
                    self.player.on_ground = True
                    # 启动出生点暂停
                    self.player.spawn_pause = True
                    self.player.spawn_pause_timer = 30  # 0.5秒（60FPS下30帧）

    def render(self):
        """渲染游戏画面"""
        # 绘制背景
        if self.current_level == 1:
            screen.fill(SKY_BLUE)
        elif self.current_level == 2:
            screen.fill((50, 50, 100))
        elif self.current_level == 3:
            screen.fill((80, 80, 80))
        elif self.current_level == 4:
            screen.fill((40, 40, 80))  # 深蓝色背景表示新关卡

        # 绘制游戏元素
        for platform in self.level.platforms:
            screen.blit(platform.image, platform.rect)

        for block in self.level.question_blocks:
            screen.blit(block.image, block.rect)

        for enemy in self.level.enemies:
            screen.blit(enemy.image, enemy.rect)

        # 新增：绘制食人花
        if hasattr(self.level, 'piranha_plants'):
            for plant in self.level.piranha_plants:
                screen.blit(plant.image, plant.rect)

        # 新增：绘制存档点
        if hasattr(self.level, 'checkpoints'):
            for checkpoint in self.level.checkpoints:
                screen.blit(checkpoint.image, checkpoint.rect)

        for coin in self.level.coins:
            screen.blit(coin.image, coin.rect)

        screen.blit(self.player.image, self.player.rect)

        # 绘制终点
        if self.level.goal:
            pygame.draw.rect(
                screen, BROWN, (self.level.goal[0], self.level.goal[1], 10, 150))
            pygame.draw.rect(
                screen, RED, (self.level.goal[0] - 20, self.level.goal[1], 40, 20))

        # 绘制UI
        lives_text = self.small_font.render(
            f"生命: {self.player.lives}", True, WHITE)
        screen.blit(lives_text, (10, 10))

        score_text = self.small_font.render(
            f"分数: {self.player.score}", True, WHITE)
        screen.blit(score_text, (120, 10))

        # 新增：绘制三段跳按钮
        if not self.paused and not self.game_over and not self.victory:
            pygame.draw.rect(screen, self.current_button_color,
                             self.triple_jump_button)
            pygame.draw.rect(screen, WHITE, self.triple_jump_button, 2)  # 边框
            button_text = self.small_font.render(
                f"三段跳: {'开启' if self.allow_triple_jump else '关闭'}", True, WHITE)
            text_rect = button_text.get_rect(
                center=self.triple_jump_button.center)
            screen.blit(button_text, text_rect)

        level_text = self.small_font.render(
            f"关卡: {self.current_level}", True, WHITE)
        screen.blit(level_text, (SCREEN_WIDTH - 120, 10))

        # 绘制暂停/游戏结束/胜利画面
        if self.paused:
            self.draw_pause_screen()
        if self.game_over:
            self.draw_game_over_screen()
        if self.victory:
            self.draw_victory_screen()

        # 更新屏幕
        pygame.display.flip()

    # 新增：run方法 - 游戏主循环
    def run(self):
        """游戏主循环"""
        while self.running:
            # 处理事件
            self.handle_events()

            # 如果游戏没有暂停、游戏结束或胜利，则更新游戏状态
            if not self.paused and not self.game_over and not self.victory:
                self.update()

            # 渲染游戏画面
            self.render()

            # 控制帧率
            clock.tick(FPS)

    def draw_pause_screen(self):
        """绘制暂停画面"""
        pause_surface = pygame.Surface((400, 200), pygame.SRCALPHA)
        pause_surface.fill((0, 0, 0, 180))
        pause_rect = pause_surface.get_rect(
            center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2))
        screen.blit(pause_surface, pause_rect)

        pause_text = self.font.render("游戏暂停", True, WHITE)
        screen.blit(pause_text, (SCREEN_WIDTH//2 -
                    pause_text.get_width()//2, SCREEN_HEIGHT//2 - 50))

        continue_text = self.small_font.render("按P继续游戏", True, WHITE)
        screen.blit(continue_text, (SCREEN_WIDTH//2 -
                    continue_text.get_width()//2, SCREEN_HEIGHT//2 + 20))

        restart_text = self.small_font.render("按R重新开始", True, WHITE)
        screen.blit(restart_text, (SCREEN_WIDTH//2 -
                    restart_text.get_width()//2, SCREEN_HEIGHT//2 + 50))

    def draw_game_over_screen(self):
        """绘制游戏结束画面"""
        game_over_surface = pygame.Surface((400, 250), pygame.SRCALPHA)
        game_over_surface.fill((0, 0, 0, 180))
        game_over_rect = game_over_surface.get_rect(
            center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2))
        screen.blit(game_over_surface, game_over_rect)

        game_over_text = self.font.render("游戏结束", True, RED)
        screen.blit(game_over_text, (SCREEN_WIDTH//2 -
                    game_over_text.get_width()//2, SCREEN_HEIGHT//2 - 80))

        final_score_text = self.small_font.render(
            f"最终分数: {self.player.score}", True, WHITE)
        screen.blit(final_score_text, (SCREEN_WIDTH//2 -
                    final_score_text.get_width()//2, SCREEN_HEIGHT//2))

        restart_text = self.small_font.render("按R重新开始", True, WHITE)
        screen.blit(restart_text, (SCREEN_WIDTH//2 -
                    restart_text.get_width()//2, SCREEN_HEIGHT//2 + 50))

    def draw_victory_screen(self):
        """绘制胜利画面"""
        victory_surface = pygame.Surface((400, 250), pygame.SRCALPHA)
        victory_surface.fill((0, 0, 0, 180))
        victory_rect = victory_surface.get_rect(
            center=(SCREEN_WIDTH//2, SCREEN_HEIGHT//2))
        screen.blit(victory_surface, victory_rect)

        victory_text = self.font.render("恭喜通关！", True, YELLOW)
        screen.blit(victory_text, (SCREEN_WIDTH//2 -
                    victory_text.get_width()//2, SCREEN_HEIGHT//2 - 80))

        final_score_text = self.small_font.render(
            f"最终分数: {self.player.score}", True, WHITE)
        screen.blit(final_score_text, (SCREEN_WIDTH//2 -
                    final_score_text.get_width()//2, SCREEN_HEIGHT//2))

        restart_text = self.small_font.render("按R重新开始", True, WHITE)
        screen.blit(restart_text, (SCREEN_WIDTH//2 -
                    restart_text.get_width()//2, SCREEN_HEIGHT//2 + 50))

    def reset_level(self):
        """重置关卡"""
        """重置当前关卡"""
        # 如果当前处于胜利状态，则重置到第一关
        if self.victory:
            self.current_level = 1

        self.level = Level(self.current_level)

        # 重置玩家位置 - 根据不同关卡设置正确的初始位置
        self.player.rect.x = 100
        # 第三关特殊处理，确保玩家站在出生点平台上
        if self.current_level == 3:
            self.player.rect.y = SCREEN_HEIGHT - 130  # 略低于平台，确保落在平台上
        else:
            self.player.rect.y = SCREEN_HEIGHT - 100

        self.player.velocity_x = 0
        self.player.velocity_y = 0
        self.player.on_ground = True  # 确保玩家在地面上
        self.player.game_over = False  # 重置玩家的游戏结束状态
        # 重置三段跳设置
        self.player.max_jumps = 3 if self.allow_triple_jump else 2
        # 重置游戏状态
        self.paused = False
        self.game_over = False
        self.victory = False
        # 重置玩家生命值和分数
        self.player.lives = 3
        self.player.score = 0

    # 新增：set_checkpoint方法（虽然第四关不需要，但为了代码完整性）

    def set_checkpoint(self, x, y):
        """设置存档点位置"""
        self.checkpoint_x = x
        self.checkpoint_y = y


# 如果直接运行此文件，启动游戏
if __name__ == "__main__":
    game = Game()
    game.run()
    pygame.quit()
    sys.exit()
